<?php

namespace XF {
    
    Loader::loadModel('News');

    final class NewsController extends AbstractController {

        public static function Action() {
            URLManager::setPath('news', 'page', array(1));
            URLManager::redirect();
        }

        public static function pageAction($params) {
            if (!isset($params[0]) || $params[0] < 0) {
                URLManager::setPath('news', 'page', array(1));
                URLManager::redirect();
            }
            $pageNum =& $params[0];
            $newsPerPage = self::getConfig('newsPerPage');
            if (is_null($newsPerPage)) {
                $newsPerPage = 10;
            }
            
            $quantity = NewsModel::getQuantity();
            $maxPage = ceil($quantity / $newsPerPage);
            
            if ($pageNum > $maxPage) {
                URLManager::setPath('news', 'page', array($maxPage));
                URLManager::redirect();
            }
            
            LayoutManager::setView('main', 'news', 'page');
            
            $news = NewsModel::getPage($pageNum, $newsPerPage);
            $count = count($news);
            if ($count > 0) {
                $start = ($pageNum-1)*$newsPerPage+1;
                $end = $start + $count - 1;
                LayoutManager::setVar('info', 'Showing '.$start.' to '.$end.' of '.$quantity);
                
                LayoutManager::setRepeatID('news');
                foreach ($news as $NewsModel) {
                    URLManager::setPath('news', 'view', array($NewsModel->getId()));
                    LayoutManager::setRepeatVar('link',   URLManager::getURI());
                    LayoutManager::setRepeatVar('title',  $NewsModel->getTitle());
                    LayoutManager::setRepeatVar('date',   $NewsModel->getPostDate());
                    LayoutManager::setRepeatVar('author', $NewsModel->getAuthor());
                    LayoutManager::setRepeatVar('content', $NewsModel->getContent());
                }
                
                LayoutManager::setRepeatID('news-links');
                for ($i = 1; $i <= $maxPage; ++$i) {
                    if ($i == $pageNum) {
                        $link = $i;
                    } else {
                        URLManager::setPath('news', 'page', array($i));
                        $link = '<a href="'.URLManager::getURI().'">'.$i.'</a>';
                    }
                    LayoutManager::setRepeatVar('link', $link);
                }
            } else {
                LayoutManager::setVar('info', "No news found.");
            }
        }

    }

}
?>
